package com.qms.qep.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.qms.common.annotation.Log;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.enums.BusinessType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("/qep/file")
public class FileUploadController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
    
    @Value("${qms.upload.path:/uploads}")
    private String uploadBasePath;

    /**
     * 通用文件上传接口 - 用于富文本编辑器
     */
    @ApiOperation("通用文件上传")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        try {
            // 获取文件原名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "unknown";
            }
            
            // 获取文件扩展名
            String fileExt = "";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0) {
                fileExt = originalFilename.substring(dotIndex);
            }
            
            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + fileExt;
            
            // 确保目录存在
            String uploadDir = getUploadDir();
            Files.createDirectories(Paths.get(uploadDir));
            
            // 保存文件
            Path targetPath = Paths.get(uploadDir, uniqueFileName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            // 组装响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("url", "/uploads/" + uniqueFileName); // 返回相对路径
            data.put("filename", uniqueFileName);
            data.put("originalFilename", originalFilename);
            
            return AjaxResult.success("上传成功", data);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * WordPaster 专用上传接口
     */
    @ApiOperation("WordPaster文件上传")
    @PostMapping(value = "/wordpaster/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult wordpasterUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        try {
            // 获取文件原名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "unknown";
            }
            
            // 获取文件扩展名
            String fileExt = "";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0) {
                fileExt = originalFilename.substring(dotIndex);
            }
            
            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + fileExt;
            
            // 确保目录存在
            String uploadDir = getUploadDir() + "/wordpaster/";
            Files.createDirectories(Paths.get(uploadDir));
            
            // 保存文件
            Path targetPath = Paths.get(uploadDir, uniqueFileName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            // 组装WordPaster需要的特定格式响应
            Map<String, Object> data = new HashMap<>();
            data.put("uploaded", 1);
            data.put("url", "/uploads/wordpaster/" + uniqueFileName);
            data.put("fileName", uniqueFileName);
            
            return AjaxResult.success(data);
        } catch (Exception e) {
            log.error("WordPaster文件上传失败", e);
            return error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 富文本编辑器图片上传
     */
    @ApiOperation("富文本编辑器图片上传")
    @PostMapping("/upload/image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return error("只允许上传图片文件");
        }
        
        try {
            // 获取文件原名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "image.png";
            }
            
            // 获取文件扩展名
            String fileExt = ".png";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0) {
                fileExt = originalFilename.substring(dotIndex);
            }
            
            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + fileExt;
            
            // 确保目录存在
            String uploadDir = getUploadDir() + "/images/";
            Files.createDirectories(Paths.get(uploadDir));
            
            // 保存文件
            Path targetPath = Paths.get(uploadDir, uniqueFileName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            // 组装响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("url", "/uploads/images/" + uniqueFileName);
            data.put("title", originalFilename);
            data.put("filename", uniqueFileName);
            data.put("originalFilename", originalFilename);
            
            return AjaxResult.success("图片上传成功", data);
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return error("图片上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取上传目录
     */
    private String getUploadDir() {
        // 先尝试从配置中获取绝对路径
        if (uploadBasePath.startsWith("/") || uploadBasePath.contains(":")) {
            return uploadBasePath;
        }
        
        // 否则使用相对路径
        String userDir = System.getProperty("user.dir");
        return userDir + File.separator + uploadBasePath;
    }
} 